<template>
  <div class="auth-container">
    <!-- 背景装饰元素 -->
    <div class="bg-shapes">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
      <div class="shape shape-3"></div>
    </div>
    
    <div class="auth-card">
      <!-- 卡片装饰 -->
      <div class="card-decoration"></div>
      
      <div class="auth-header">
        <h2 class="auth-title">{{ isLogin ? "用户登录" : "用户注册" }}</h2>
        <p class="auth-subtitle">
          {{
            isLogin ? "欢迎回来，请登录您的账户" : "创建新账户，开启您的旅程"
          }}
        </p>
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="isLogin"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0"
        size="large"
        @submit.prevent="handleLogin"
        class="auth-form"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            class="custom-input"
          >
            <template #prefix>
              <i class="icon-user input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            class="custom-input"
            show-password
          >
            <template #prefix>
              <i class="icon-lock input-icon"></i>
            </template>
          </el-input>
        </el-form-item>
        
        <div class="captcha-container">
          <el-form-item prop="captcha" class="captcha-input">
            <el-input
              v-model="loginForm66.captcha"
              placeholder="验证码"
              class="custom-input"
            >
              <template #prefix>
                <i class="icon-shield input-icon"></i>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="captcha-image-container" @click="getCaptcha">
            <el-image
              :src="captchaImage"
              class="captcha-image"
              fit="cover"
            >
              <template #error>
                <div class="captcha-error">
                  <i class="icon-refresh"></i>
                  <span>点击刷新</span>
                </div>
              </template>
            </el-image>
            <div class="captcha-tip">点击刷新</div>
          </div>
        </div>

        <el-form-item>
          <el-button type="primary" class="auth-button" @click="handleLogin" :loading="loading">
            <span v-if="!loading">登录</span>
            <span v-else>登录中...</span>
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="0"
        size="large"
        @submit.prevent="handleRegister"
        class="auth-form"
      >
        <!-- 头像上传 -->
        <el-form-item prop="avatar" class="avatar-upload-item">
          <div class="avatar-upload-container">
            <div class="avatar-label">上传头像</div>
            <el-upload
              name="file"
              class="avatar-uploader"
              action="http://localhost:9520/serviceoss/fileoss/uploadAvatarToOss"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <div class="avatar-preview">
                <img
                  v-if="registerForm.avatar"
                  :src="registerForm.avatar"
                  class="avatar-image"
                />
                <div v-else class="avatar-placeholder">
                  <i class="icon-camera"></i>
                  <span>点击上传</span>
                </div>
                <div class="avatar-overlay">
                  <i class="icon-edit"></i>
                </div>
              </div>
            </el-upload>
            <div class="avatar-tips">支持 JPG、PNG 格式，大小不超过 2MB</div>
          </div>
        </el-form-item>

        <el-form-item prop="userName">
          <el-input
            v-model="registerForm.userName"
            placeholder="请输入用户名"
            class="custom-input"
          >
            <template #prefix>
              <i class="icon-user input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            class="custom-input"
          >
            <template #prefix>
              <i class="icon-phone input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            class="custom-input"
            show-password
          >
            <template #prefix>
              <i class="icon-lock input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            class="custom-input"
            show-password
          >
            <template #prefix>
              <i class="icon-lock input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="idCard">
          <el-input
            v-model="registerForm.idCard"
            placeholder="请输入身份证号"
            class="custom-input"
          >
            <template #prefix>
              <i class="icon-id-card input-icon"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="auth-button" @click="handleRegister" :loading="loading">
            <span v-if="!loading">注册</span>
            <span v-else>注册中...</span>
          </el-button>
        </el-form-item>
      </el-form>

      <div class="auth-switch">
        <span>
          {{ isLogin ? "还没有账户？" : "已有账户？" }}
          <a class="switch-link" @click="toggleForm">{{ isLogin ? "立即注册" : "立即登录" }}</a>
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted,ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";

//导入用户的pinia
import { useCounterStore } from "@/stores/counter.js";
import axios from "axios";
import authHttp from '@/util/request'

const userStore = useCounterStore()
const loading = ref(false)

const loginForm66=ref({
  captcha:'',
  captchaKey:'',
})

const captchaImage=ref('')

//验证码图片
const getCaptcha = async () => {
  try {
    const { data: response } = await axios.get(`/advertisement/captcha/get`)
    console.log(response,'验证码图片')
    captchaImage.value  = response.base64Img
    // 设置全局变量
    loginForm66.value.captchaKey = response.captchaKey
    console.log(loginForm66,'验证码key')
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

onMounted(() => { 
  //获取验证码
  getCaptcha()
});

//查询用户信息
const getUserInfo = async () => {
  const { data: response } = await authHttp.post('/eduservice/user/loginInfo')
  userStore.userId = response.name.userId
  userStore.username = response.name.userName
}

//根据id查询头像
const getAvatar = async () => {
  const { data: response } = await axios.get(`/advertisement/user/${userStore.userId}`)
  // 设置全局变量
  userStore.avatar = response.data.user.avatar
}

// 响应式数据
const isLogin = ref(true);
const loginFormRef = ref();
const registerFormRef = ref();

// 登录表单数据
const loginForm = reactive({
  phone: "",
  password: "",
});

// 注册表单数据
const registerForm = reactive({
  userName: "",
  phone: "",
  password: "",
  confirmPassword: "",
  idCard: "",
  avatar: "",
});

// 登录表单验证规则
const loginRules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
};

// 注册表单验证规则
const registerRules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度在2-20个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  idCard: [
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
};

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 处理头像上传
const handleAvatarSuccess = (options) => {
  if(options.code == 20000){
    registerForm.avatar = options.data.url
  } 
};

// 切换登录/注册表单
const toggleForm = () => {
  isLogin.value = !isLogin.value;
  // 重置表单
  if (loginFormRef.value) {
    loginFormRef.value.resetFields();
  }
  if (registerFormRef.value) {
    registerFormRef.value.resetFields();
    registerForm.avatar = ""; // 清空头像
  }
};

// 处理登录
const handleLogin = async () => {
  loading.value = true
  try {
    //获取验证码
    const { data: response } = await axios.post(`/advertisement/captcha/get`, loginForm66.value)
    console.log(response,'验证码发送')
    
    if(response == 'ok'){
      loginFormRef.value.validate(async valid => {
        if (valid){
          // 获取用户信息
          let res = await axios.post("/eduservice/user/Login", loginForm);
          if(res.data.data.token != "密码错误" && res.data.data.token != "用户名为空"){
            ElMessage.success("登录成功")
            // 保存token到pinia中持久化
            userStore.token = res.data.data.token
            //调用查询用户信息
            await getUserInfo()
            await getAvatar()
            //跳转到首页
            window.location.href = '/SimpleCarousel'
          } else if(res.data.data.token == "密码错误") {
            ElMessage.error("密码错误")
          } else if(res.data.data.token == "用户名为空"){
            ElMessage.error("用户名为空")
          }
        }
      })
    } else {
      ElMessage.error("验证码错误")
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error("登录失败，请重试")
  } finally {
    loading.value = false
  }
};  

// 处理注册
const handleRegister = async () => {
  loading.value = true
  try {
    registerFormRef.value.validate(async valid => {
      if (valid){
        // 发送请求注册
        console.log(1111, registerForm)
        let res2 = await axios.post("/advertisement/user/addUser", registerForm);
        ElMessage.success("注册成功")
        isLogin.value = true
        //跳转到登录界面
        router.push('/login')
      }
    })
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error("注册失败，请重试")
  } finally {
    loading.value = false
  }
};
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.bg-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -150px;
  right: -100px;
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  left: -80px;
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  right: 10%;
}

.auth-card {
  width: 100%;
  max-width: 460px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px 35px;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.card-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 20px 20px 0 0;
}

.auth-header {
  text-align: center;
  margin-bottom: 30px;
}

.auth-title {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 10px;
  font-weight: 600;
  background: linear-gradient(90deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.auth-subtitle {
  font-size: 15px;
  color: #7f8c8d;
  line-height: 1.5;
}

.auth-form {
  margin-top: 20px;
}

.custom-input {
  border-radius: 10px;
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: 10px;
  padding: 5px 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.custom-input :deep(.el-input__wrapper:hover),
.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.input-icon {
  color: #667eea;
  font-size: 16px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.captcha-input {
  flex: 1;
}

.captcha-image-container {
  position: relative;
  cursor: pointer;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
  transition: all 0.3s;
}

.captcha-image-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.captcha-image {
  width: 120px;
  height: 40px;
  display: block;
}

.captcha-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 12px;
}

.captcha-tip {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 10px;
  text-align: center;
  padding: 2px;
  opacity: 0;
  transition: opacity 0.3s;
}

.captcha-image-container:hover .captcha-tip {
  opacity: 1;
}

.auth-button {
  width: 100%;
  height: 48px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border: none;
  margin-top: 10px;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.auth-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.auth-button:active {
  transform: translateY(0);
}

.auth-switch {
  text-align: center;
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.switch-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.switch-link:hover {
  color: #764ba2;
  text-decoration: underline;
}

/* 头像上传样式 */
.avatar-upload-item {
  margin-bottom: 30px;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.avatar-label {
  font-size: 16px;
  color: #2c3e50;
  font-weight: 500;
}

.avatar-uploader {
  cursor: pointer;
}

.avatar-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: 2px dashed #dcdfe6;
  overflow: hidden;
}

.avatar-preview:hover {
  border-color: #667eea;
  transform: scale(1.05);
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-placeholder {
  color: #c0c4cc;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  height: 100%;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 50%;
}

.avatar-tips {
  font-size: 12px;
  color: #909399;
  text-align: center;
}

/* 图标字体 */
@font-face {
  font-family: 'iconfont';
  src: url('//at.alicdn.com/t/c/font_1234567_abcdefghijk.woff2') format('woff2');
}

.icon-user:before { content: "👤"; }
.icon-lock:before { content: "🔒"; }
.icon-shield:before { content: "🛡️"; }
.icon-phone:before { content: "📱"; }
.icon-id-card:before { content: "🆔"; }
.icon-camera:before { content: "📷"; }
.icon-edit:before { content: "✏️"; }
.icon-refresh:before { content: "🔄"; }

.input-icon {
  font-style: normal;
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-card {
    padding: 30px 20px;
    margin: 10px;
  }
  
  .captcha-container {
    flex-direction: column;
  }
  
  .captcha-image-container {
    align-self: center;
  }
}

/* 动画效果 */
.auth-card {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态 */
:deep(.el-button--primary.is-loading) {
  opacity: 0.8;
}
</style>